package com.vayne.demo;

import com.vayne.bean.Person;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Map;

/**
 * 使用 Builder 构建 Bean
 * {@link org.springframework.beans.factory.support.BeanDefinitionBuilder}
 *
 * @author xuerui.zhang
 * @since 2020/1/19 下午2:28
 */
public class BeanDefinitionBuilderDemo {

    public static void main(String[] args) {
        // 0、创建上下文
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 1、通过 BeanDefinitionBuilder 创建 Bean
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Person.class);
        beanDefinitionBuilder.addPropertyValue("name", "BeanDefinitionBuilder");
        beanDefinitionBuilder.addPropertyValue("age", 10);

        // 2、通过 GenericBeanDefinition 创建 Bean
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(Person.class);
        MutablePropertyValues values = new MutablePropertyValues();
        values.add("name", "GenericBeanDefinition");
        values.add("age", 20);
        genericBeanDefinition.setPropertyValues(values);

        // 3、注册 Bean
        applicationContext.registerBeanDefinition("p1", beanDefinitionBuilder.getBeanDefinition());
        applicationContext.registerBeanDefinition("p2", genericBeanDefinition);

        // 4、启动应用上下文
        applicationContext.refresh();

        Map<String, Person> courseMap = ((ListableBeanFactory) applicationContext).getBeansOfType(Person.class);
        System.out.println(courseMap);

    }
}
